package env

import (
	"bufio"
	"gitee.com/kushao/logs"
	"os"
	"strings"
	"sync"
)

var (
	FileName = ".env"
	Data     = map[string]string{}
	status   bool
	Rwlock   sync.RWMutex
)

func Get(key string) string {
	if !status {
		Load()
		status = true
	}
	key = strings.ToLower(key)
	Rwlock.RLock()
	data := Data[key]
	Rwlock.RUnlock()
	return data
}
func Gets(key string) map[string]string {
	if !status {
		Load()
		status = true
	}
	if key == "." {
		return Data
	}
	key = strings.ToLower(key)
	var data = map[string]string{}
	Rwlock.RLock()
	for k, v := range Data {
		if key == "" {
			if strings.Index(k, ".") < 0 {
				data[k] = v
			}
			continue
		}
		if strings.Index(k, key+".") == 0 {
			data[k[len(key+"."):]] = v
		}
	}
	Rwlock.RUnlock()
	return data
}
func Load() {
	openFile, err := os.OpenFile(FileName, os.O_RDONLY, os.ModePerm)
	if err != nil {
		logs.Error("[env.Read]", 1, err.Error())
		return
	}
	defer func(openFile *os.File) {
		_ = openFile.Close()
	}(openFile)
	scanner := bufio.NewScanner(openFile)
	var fieldPrefix string
	Rwlock.Lock()
	data := map[string]string{}
	for scanner.Scan() {
		line := scanner.Text()
		if len(line) == 0 || line[0] == '#' {
			continue
		}
		s := strings.TrimSpace(line)
		if len(s) == 0 || s[0] == '#' {
			continue
		}
		if strings.Index(s, "[") == 0 && strings.Index(s, "]") == len(s)-1 {
			s = s[1 : len(s)-1]
			s = strings.TrimSpace(s)
			if len(s) == 0 {
				continue
			}
			fieldPrefix = s
			continue
		}
		i := strings.Index(s, "=")
		if i <= 0 {
			continue
		}
		key := strings.TrimSpace(s[:i])
		if len(key) == 0 {
			continue
		}
		if fieldPrefix != "" {
			key = fieldPrefix + "." + key
		}
		val := strings.TrimSpace(s[i+1:])
		key = strings.ToLower(key)
		data[key] = val
	}
	Data = data
	Rwlock.Unlock()
}
